package com.blog.service.impl;

import com.blog.domain.ResponseResult;
import com.blog.domain.entity.LoginUser;
import com.blog.domain.entity.User;
import com.blog.domain.vo.BlogUserLoginVo;
import com.blog.domain.vo.UserInfoVo;
import com.blog.service.BlogLoginService;
import com.blog.utils.BeanCopyUtils;
import com.blog.utils.JwtUtil;
import com.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;


@Service
public class BlogLoginServiceImpl implements BlogLoginService {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	/**登陆
	 *
	 * @param user
	 * @return
	 */
	@Override
	public ResponseResult login(User user) {
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
		Authentication authenticate = authenticationManager.authenticate(authenticationToken);
		//判断是否认证通过
		if(Objects.isNull(authenticate)){
			throw new RuntimeException("用户名或密码错误");
		}
		//获取userid 生成token
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		String userId = loginUser.getUser().getId().toString();
		String jwt = JwtUtil.createJWT(userId);
		//把用户信息存入redis
		redisCache.setCacheObject("bloglogin:"+userId,loginUser);

		//把token和userinfo封装 返回
		//把User转换成UserInfoVo
		UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
		BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);
		return ResponseResult.okResult(vo);
	}

	/**退出登录
	 *
	 * @return
	 */
	@Override
	public ResponseResult logout() {
		//从token中获取userid
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		Long userid = loginUser.getUser().getId();
		//删除Redis用户信息
		redisCache.deleteObject("bloglogin"+userid);
		return ResponseResult.okResult();
	}
}
